#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/24 10:49
    Desc  :
--------------------------------------
"""
from mongoengine.base import TopLevelDocumentMetaclass

from common.libs.QuerySetUtils import QuerySetUtils
from common.libs.paginationUtils import ListPaginationUtils
from common.libs.queryListUtils import QueryListUtils


class BaseServices:

    def __init__(self, document: TopLevelDocumentMetaclass):
        self.document = document

    # 查询所有
    def find_all(self):

        queryset =  self.document.objects().all()

        return queryset

    # 根据id查询
    def find_by_id(self, id):

        queryset = self.document.objects(id = id).first()

        return queryset

    # 分页查询
    def pagination(self, queries='icontains', **kwargs):
        # 构建模糊查询字段
        data = QueryListUtils(kwargs).filter_by(queries)

        # 开始查询
        queryset = self.document.objects(**data).order_by('id')

        # 分液器
        return ListPaginationUtils(queryset, **data).items

    # 新增
    def save(self, **kwargs):

        kwargs = QuerySetUtils(self.document).filterField(kwargs)

        queryset = self.document(**kwargs)

        queryset.save()

        return queryset

    # 更新
    def update(self, id, **kwargs):

        queryset = self.document.objects(id = id)

        queryset.update(**kwargs)

        return queryset

    # 删除
    def delete(self, id):

        queryset = self.document.objects(id = id)

        queryset.delete()